// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// d [author] rhyme_lph
// A [email]  rhymelph@gmail.com
// c [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/contact_person_entity.dart';
import 'package:finance_app/src/http_service/http_contact_person_service.dart';
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/provider/dashboard/contact/detail/contact_detail_person_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class NewContactPersonProvider extends BaseProvider {
  TextEditingController nameController = TextEditingController();
  FocusNode nameFocusNode = FocusNode();

  TextEditingController phoneNumberController = TextEditingController();
  FocusNode phoneNumberFocusNode = FocusNode();

  TextEditingController emailController = TextEditingController();
  FocusNode emailFocusNode = FocusNode();

  TextEditingController positionController = TextEditingController();
  FocusNode positionFocusNode = FocusNode();

  bool isCheckPrimary = false;

  String countryCode = '+65';

  int id;

  int contactId;

  List<String> menuList = ['Edit', 'Delete'];

  @override
  void dispose() {
    super.dispose();
    nameFocusNode.dispose();
    nameController.dispose();
    phoneNumberController.dispose();
    phoneNumberFocusNode.dispose();
    emailController.dispose();
    emailFocusNode.dispose();
    positionController.dispose();
    positionFocusNode.dispose();
  }

  @override
  Future get dataFuture => null;

  void unFocus() {
    nameFocusNode.unfocus();
    phoneNumberFocusNode.unfocus();
    emailFocusNode.unfocus();
    positionFocusNode.unfocus();
  }

  void onChangePrimary() {
    isCheckPrimary = !isCheckPrimary;
    update();
  }

  void updateCountryCode(value) {
    countryCode = value;
    update();
  }

  void onSave() async {
    unFocus();
    if (nameController.text.length == 0) {
      showToast(S.current.please_enter_name);
      return;
    }
    if (phoneNumberController.text.length == 0) {
      showToast(S.current.please_enter_phone_number);
      return;
    }
    if (emailController.text.length == 0) {
      showToast(S.current.please_enter_email);
      return;
    }
    if (positionController.text.length == 0) {
      showToast(S.current.please_enter_position);
      return;
    }

    ContactPersonEntity entity;
    if (isEdit == true) {
      await post(
          HttpContactPersonService.updateContact(
              id,
              contactId,
              nameController.text,
              countryCode,
              phoneNumberController.text,
              emailController.text,
              positionController.text,
              isCheckPrimary ? 1 : 0),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        entity = getEntityFromResult<ContactPersonEntity>(result);
      });
    } else {
      await post(
          HttpContactPersonService.createContact(
              contactId,
              nameController.text,
              countryCode,
              phoneNumberController.text,
              emailController.text,
              positionController.text,
              isCheckPrimary ? 1 : 0),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        entity = getEntityFromResult<ContactPersonEntity>(result);
      });
    }
    if (entity != null) {
      final pro = Providers.get<BusinessContactDetailProvider>(
          RouterGenProviders.businessContactDetailPage, null);
      if (pro != null) {
        pro
            .getChildProvider<ContactDetailPersonProvider>()
            ?.onUpdateContact(entity);
      }
      obtainContext?.call((context) {
        Navigator.of(context).pop(entity);
      });
    }
  }

  bool isEdit;

  void initContactPerson(ContactPersonEntity data) {
    if (data == null) return;
    id = data.id;
    isEdit = false;
    nameController.text = data.name;
    phoneNumberController.text = data.phoneNumber;
    emailController.text = data.email;
    positionController.text = data.position;
    isCheckPrimary = data.isPrimary == 1;
    countryCode = data.countryCode;
    contactId = data.contactId;
  }

  void onSelectMenu(String value) {
    switch (menuList.indexOf(value)) {
      case 0:
        isEdit = !isEdit;
        update();
        break;
      case 1:
        onDelete();
        break;
    }
  }

  void onDelete() {
    obtainContext?.call((context) async {
      bool isSuccess = await showDeleteContactPersonInfoBottomSheet(context);
      if (isSuccess == true) {
        isSuccess = false;
        await post(HttpContactPersonService.deleteContact(id),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          final pro = Providers.get<BusinessContactDetailProvider>(
              RouterGenProviders.businessContactDetailPage, null);
          if (pro != null) {
            pro
                .getChildProvider<ContactDetailPersonProvider>()
                ?.onDeleteContact(id);
          }
          await showContactPersonSuccessBottomSheet(context);
          Navigator.of(context).pop();
        }
      }
    });
  }

  void onCall() async {
    await launch(
        Uri(scheme: 'tel', path: phoneNumberController.text).toString());
  }

  void onEmail() async {
    await launch(Uri(scheme: 'mailto', path: emailController.text).toString());
  }
}
